//import axios from "./config";
//import * as url from "./url";
import { Message, MessageBox, Notification } from 'element-ui';
import * as api from './url'
import {guid} from '../util/tools'
import auth, {authLogin} from '../util/auth'

// 支持参数及promise两种方式调用
// 内置未application/json;charset=UTF-8, 根据有需要开放参数传递
function ajax(type, url, data, suc, err, comp){
	if(type==='POST'){
		data=data||{};
	}
	let headers = {};
	if(authLogin){
		headers.Authorization = 'Bearer '+auth.getToken();
	}
	return new Promise((resolve, reject)=>{
		$.ajax({
			type: type,
			url: url,
			data: type==='POST'?JSON.stringify(data):data,
			contentType: type==='POST'?'application/json; charset=UTF-8':undefined,
			xhrFields:{
				withCredentials: true,
			},
			crossDomain: true,
			headers,
			success:function(data, textStatus, xhr){
				// suc
				if(data && data.code===2000){
					if(suc) {
						suc(data.data);
					}
					resolve(data.data);
					return;
				}

				if(authLogin){
					if(data && [4000, 4001].includes(data.code)){
						auth.clearToken();
						location.href='/#/login';
						return;
					}
				}

				// err
				if(data){
					toast(`${data.msg}`, "error")
				}
				if(err){
					err(xhr, textStatus, data)
				}
				reject(xhr, textStatus, data)
			},
			error:function(xhr, textStatus, errorThrown){
				if((xhr.status===403 || xhr.status===401)){
					if(authLogin){
						auth.clearToken();
						location.href='/#/login';
					}else{
						location.href='/logout';
					}
					return;
				}

				let errMsg = '';
				try{
					let errObj = JSON.parse(xhr.responseText);
					if(errObj && errObj.code && errObj.msg){
						errMsg = errObj.msg;
						// errMsg = `${errObj.msg}(错误代码：${errObj.code})`;
					}else{
						errMsg=`系统开小差了，请您稍后再试吧~（${xhr.status}）`
					}
				}catch(e){
					errMsg=`系统开小差了，请您稍后再试吧~（${xhr.status}）`
				}

				toast(errMsg, "error")

				if(err) {
					err(xhr, textStatus, errorThrown);
				}
				reject(xhr, textStatus, errorThrown);
			},
			complete:function(xhr, textStatus){
				if(comp){
					comp(xhr, textStatus)
				}
			}
		})
	})
}

export const get = (url, data, suc, err, comp) => {
	return ajax("GET", url, data, suc, err, comp)
};

export const post = (url, data, suc, err, comp) => {
	return ajax("POST", url, data, suc, err, comp)
};

// type: 'success' | 'warning' | 'info' | 'error'
export const toast = (msg, type="success")=>{
	Message({
		message: msg,
		type: type,
	})
}

// type: 'success' | 'warning' | 'info' | 'error'
export const notify = (msg, title="", type="info")=>{
	Notification({
		title: title,
		message: msg,
		type: type
	})
}

// type: 'success' | 'warning' | 'info' | 'error'
export const alert = (msg, cb, title="", type="info", okText="确定")=>{
	MessageBox({
		title: title,
		message: msg,
		type: type,
		callback: cb,
		confirmButtonText: okText,
	})
}

// type: 'success' | 'warning' | 'info' | 'error'
export const confirm = (msg, ok, cancel, title="", type="warning", okText="确定", cancelText="取消")=>{
	if(ok || cancel){
		MessageBox({
			title: title,
			message: msg,
			type: type,
			confirmButtonText: okText,
			cancelButtonClass: cancelText,
			showCancelButton: true,
		}).then(ok).catch(cancel);
	}else{
		return MessageBox({
			title: title,
			message: msg,
			type: type,
			confirmButtonText: okText,
			cancelButtonClass: cancelText,
			showCancelButton: true,
		});
	}

}
